$fetch() と fetch() の違い
fetch
低レベル関数
$fetch
fetch() をラップしている
DX
code:js
// fetch()
const res = await fetch("/api/todos");
const data = await res.json();
// $fetch()
const data = await $fetch("/api/todos");
code:ts
interface Todo = { id: string; title: string };
const todos = await $fetch<Todo[]>("/api/todos");
code:ts
const data = await $fetch("/api/search", {
query: { q: "nuxt", limit: 10 },
});
// fetch() だと URLSearchParams を組み立てる必要あり
fetch() はネットワークのみ reject、HTTP ステータス 400, 500 はreject しない -> 自分でチェック
一方 $fetch() は HTTP エラーも例外として throw code:ts
try {
await $fetch("/api/404");
} catch(e: unknown) {
console.error(error status: ${e.statuts}, e)
}